import { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/24/outline";
import { useMemo } from "react";

const CompactPagination = ({
  currentPage, // 直接使用父组件传递的当前页码
  totalPages,
  onPageChange,
}) => {
  // 删除所有内部状态，完全使用受控模式

  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages) return;
    onPageChange?.(page); // 直接通知父组件
  };

  const getPageNumbers = useMemo(() => {
    const generator = () => {
      if (totalPages <= 1) return [];
      if (totalPages <= 5) {
        return Array.from({ length: totalPages }, (_, i) => i + 1);
      }

      const pages = new Set([1, totalPages]);
      const lower = Math.max(2, currentPage - 1);
      const upper = Math.min(totalPages - 1, currentPage + 1);

      for (let i = lower; i <= upper; i++) {
        pages.add(i);
      }

      // 处理起始和结束页码
      if (currentPage <= 3) {
        pages.add(2).add(3).add(4);
      }
      if (currentPage >= totalPages - 2) {
        pages
          .add(totalPages - 3)
          .add(totalPages - 2)
          .add(totalPages - 1);
      }

      const sorted = Array.from(pages).sort((a, b) => a - b);
      return sorted.reduce((acc, page, index) => {
        if (index > 0 && page - sorted[index - 1] > 1) {
          acc.push("...");
        }
        acc.push(page);
        return acc;
      }, []);
    };
    return generator();
  }, [totalPages, currentPage]); // 添加 memoization 优化

  if (totalPages <= 1) return null;

  return (
    <div className="flex items-center gap-2 p-2 bg-white rounded-lg shadow-sm">
      <button
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage === 1}
        className={`p-1.5 rounded-md hover:bg-gray-100 transition-colors ${
          currentPage === 1 ? "opacity-50 cursor-not-allowed" : ""
        }`}
        aria-label="Previous page"
      >
        <ChevronLeftIcon className="w-4 h-4" />
      </button>

      <div className="flex items-center gap-1">
        {getPageNumbers.map((page, index) =>
          page === "..." ? (
            <span key={`ellipsis-${index}`} className="px-2 text-gray-400">
              ...
            </span>
          ) : (
            <button
              key={page}
              onClick={() => handlePageChange(page)}
              className={`min-w-[32px] px-2 py-1 text-sm rounded-md transition-colors ${
                currentPage === page
                  ? "bg-blue-500 text-white font-medium"
                  : "text-gray-600 hover:bg-gray-100"
              }`}
              aria-current={currentPage === page ? "page" : undefined}
            >
              {page}
            </button>
          )
        )}
      </div>

      <button
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
        className={`p-1.5 rounded-md hover:bg-gray-100 transition-colors ${
          currentPage === totalPages ? "opacity-50 cursor-not-allowed" : ""
        }`}
        aria-label="Next page"
      >
        <ChevronRightIcon className="w-4 h-4" />
      </button>
    </div>
  );
};

export default CompactPagination;
